<Day6- 字典, 雜湊表>
集合,字典,雜湊表 存放不重複的值
集合 感興趣的是每個值本身 [值, 值]
字典 我們用 [鍵, 值] 形式來存放資料
雜湊表一樣 以 [鍵, 值] 形式來存放資料
字典 = 映射
雜湊 = 雜湊映射
重點!!! 衝突處理 (當雜湊值相同時如何處理)
//字典 like ES6 Map
function Dictionary(){
let items = {}
this.set =function(key,value){
items[key] = value
}
this.remove = function(key){
if(this.has(key)){
delete items[key]
return true
}else {
return false
}
}
this.has = function(key){
// 先做這個 會被set, remove呼叫
return key in items
}
this.get = function(key){
return this.has(key) ? items[key] : undefined
}
this.clear = function(){
items = {}
}
this.size = () => Object.keys(items).length
this.keys = () => Object.keys(items)
this.values = function(){
let values = {}
for (let value in items){
if(this.has(value)){
values.push(items[value])
}
}
return values
}
this.getItems = () => items
}
//雜湊表 HashTable , HashMap
function HasTable(){
let table = []
this.put = function(key, value){
let position = Hashfunction(key)
console.log(position + '-' + key );
table[position] = value
}
this.remove = function(key){
table[Hashfunction(key)] = undefined
}
this.get = (key) => table[Hashfunction(key)]
//先做雜湊函數
let Hashfunction = function(key){
let hash = 0
for (let i = 0 ; i< key.length ; i++){
hash += key.charCodeAt(i)
}
return hash % 37
}
this.print = function(){
for (var i = 0; i < table.length; ++i) {
if( table[i] !== undefined){
console.log(`${i}:${table[i]}`)
}
}
}
}
//解決衝突 1.分離鍵結 待更新
//解決衝突 2.線性探查 待更新
補充資料: